"""
燃气表模拟器
实现STS协议通信和充值功能
"""

import time
from typing import Dict, Any, Optional
from .meter_state import MeterState
from ..sts import STSProtocol, STSCrypto


class GasMeter:
    """燃气表模拟器类"""
    
    def __init__(self, meter_id: str, crypto: Optional[STSCrypto] = None):
        """
        初始化燃气表
        
        Args:
            meter_id: 表计ID
            crypto: 加密模块实例
        """
        self.meter_id = meter_id
        self.crypto = crypto or STSCrypto()
        self.protocol = STSProtocol(self.crypto)
        self.state = MeterState(meter_id)
        
        # 通信状态
        self.communication_active = False
        self.last_communication_time = 0
        
        # 模拟用气参数
        self.gas_rate = 2.5  # 气价（元/立方米）
        self.consumption_rate = 0.1  # 基础用气速率（立方米/小时）
    
    def start_communication(self) -> Dict[str, Any]:
        """
        开始通信会话
        
        Returns:
            通信会话状态
        """
        if self.communication_active:
            return {
                'success': False,
                'error': 'Communication already active'
            }
        
        # 启动STS协议会话
        session_result = self.protocol.start_session(self.meter_id)
        
        if session_result['success']:
            self.communication_active = True
            self.last_communication_time = int(time.time())
            
            return {
                'success': True,
                'session_id': session_result['session_id'],
                'meter_id': self.meter_id,
                'transfer_counter': session_result['transfer_counter']
            }
        else:
            return session_result
    
    def end_communication(self) -> Dict[str, Any]:
        """
        结束通信会话
        
        Returns:
            会话结束状态
        """
        if not self.communication_active:
            return {
                'success': False,
                'error': 'No active communication'
            }
        
        # 结束STS协议会话
        session_result = self.protocol.end_session()
        
        self.communication_active = False
        
        return {
            'success': True,
            'session_info': session_result,
            'total_communication_time': int(time.time()) - self.last_communication_time
        }
    
    def recharge(self, token: str) -> Dict[str, Any]:
        """
        充值操作
        
        Args:
            token: 充值令牌
            
        Returns:
            充值结果
        """
        if not self.communication_active:
            return {
                'success': False,
                'error': 'Communication not active'
            }
        
        # 验证令牌
        verify_result = self.protocol.verify_recharge_token(token)
        
        if not verify_result['success']:
            return verify_result
        
        token_info = verify_result['token_info']
        amount = token_info['amount']
        transfer_counter = token_info['transfer_counter']
        
        # 检查传输计数器
        if not self.state.update_transfer_counter(transfer_counter):
            return {
                'success': False,
                'error': 'Invalid transfer counter'
            }
        
        # 执行充值
        recharge_result = self.state.add_balance(amount, token)
        
        if recharge_result['success']:
            # 重置报警状态
            self.state.reset_alarm()
            
            return {
                'success': True,
                'amount': amount,
                'amount_formatted': verify_result['amount_formatted'],
                'previous_balance': recharge_result['previous_balance'],
                'new_balance': recharge_result['new_balance'],
                'new_balance_formatted': self.state.get_status()['current_balance_formatted'],
                'transfer_counter': transfer_counter,
                'timestamp': recharge_result['timestamp']
            }
        else:
            return recharge_result
    
    def read_meter_data(self) -> Dict[str, Any]:
        """
        读取表计数据
        
        Returns:
            表计数据
        """
        if not self.communication_active:
            return {
                'success': False,
                'error': 'Communication not active'
            }
        
        # 使用STS协议读取数据
        protocol_result = self.protocol.read_meter_data()
        
        if protocol_result['success']:
            # 合并实际状态数据
            actual_status = self.state.get_status()
            
            return {
                'success': True,
                'meter_id': self.meter_id,
                'current_balance': actual_status['current_balance'],
                'current_balance_formatted': actual_status['current_balance_formatted'],
                'total_consumption': actual_status['total_consumption'],
                'status': actual_status['status'],
                'alarm_status': actual_status['alarm_status'],
                'transfer_counter': actual_status['transfer_counter'],
                'last_recharge_time': actual_status['last_recharge_time'],
                'last_consumption_time': actual_status['last_consumption_time'],
                'timestamp': protocol_result['timestamp']
            }
        else:
            return protocol_result
    
    def simulate_consumption(self, duration_hours: float = 1.0) -> Dict[str, Any]:
        """
        模拟用气
        
        Args:
            duration_hours: 模拟时长（小时）
            
        Returns:
            用气结果
        """
        # 计算用气量
        volume = self.consumption_rate * duration_hours
        
        # 执行用气
        consumption_result = self.state.consume_gas(volume, self.gas_rate)
        
        if consumption_result['success']:
            return {
                'success': True,
                'duration_hours': duration_hours,
                'volume': volume,
                'cost_cents': consumption_result['cost_cents'],
                'cost_formatted': f"{consumption_result['cost_cents'] / 100:.2f}元",
                'previous_balance': consumption_result['previous_balance'],
                'new_balance': consumption_result['new_balance'],
                'new_balance_formatted': self.state.get_status()['current_balance_formatted'],
                'total_consumption': consumption_result['total_consumption'],
                'timestamp': consumption_result['timestamp']
            }
        else:
            return consumption_result
    
    def get_meter_status(self) -> Dict[str, Any]:
        """
        获取表计状态
        
        Returns:
            表计状态信息
        """
        status = self.state.get_status()
        
        return {
            'meter_id': self.meter_id,
            'communication_active': self.communication_active,
            'current_balance': status['current_balance'],
            'current_balance_formatted': status['current_balance_formatted'],
            'total_consumption': status['total_consumption'],
            'status': status['status'],
            'alarm_status': status['alarm_status'],
            'transfer_counter': status['transfer_counter'],
            'gas_rate': self.gas_rate,
            'consumption_rate': self.consumption_rate,
            'last_recharge_time': status['last_recharge_time'],
            'last_consumption_time': status['last_consumption_time'],
            'last_communication_time': self.last_communication_time
        }
    
    def get_recharge_history(self, limit: int = 10) -> list:
        """
        获取充值历史
        
        Args:
            limit: 返回记录数量限制
            
        Returns:
            充值历史记录
        """
        return self.state.get_recharge_history(limit)
    
    def get_consumption_history(self, limit: int = 10) -> list:
        """
        获取用气历史
        
        Args:
            limit: 返回记录数量限制
            
        Returns:
            用气历史记录
        """
        return self.state.get_consumption_history(limit)
    
    def set_gas_rate(self, rate: float) -> bool:
        """
        设置气价
        
        Args:
            rate: 新气价（元/立方米）
            
        Returns:
            设置是否成功
        """
        if rate > 0:
            self.gas_rate = rate
            return True
        return False
    
    def set_consumption_rate(self, rate: float) -> bool:
        """
        设置用气速率
        
        Args:
            rate: 新用气速率（立方米/小时）
            
        Returns:
            设置是否成功
        """
        if rate >= 0:
            self.consumption_rate = rate
            return True
        return False
    
    def reset_meter(self) -> Dict[str, Any]:
        """
        重置表计（仅用于测试）
        
        Returns:
            重置结果
        """
        if self.communication_active:
            self.end_communication()
        
        # 重新初始化状态
        self.state = MeterState(self.meter_id)
        
        return {
            'success': True,
            'message': 'Meter reset successfully',
            'meter_id': self.meter_id
        }
    
    def send_command(self, command: str, parameters: Optional[Dict] = None) -> Dict[str, Any]:
        """
        发送命令到表计
        
        Args:
            command: 命令类型
            parameters: 命令参数
            
        Returns:
            命令执行结果
        """
        if not self.communication_active:
            return {
                'success': False,
                'error': 'Communication not active'
            }
        
        return self.protocol.send_command(command, parameters)
